package outputstream_;

import org.junit.jupiter.api.Test;

import java.io.*;

/**
 * @author DCSGO
 * @version 1.0
 */
@SuppressWarnings({"all"})
public class FileOutputStream_ {
    /**
     * FileOutputStream
     * 在a.txt中写入"hi Perfect World!"
     * 再读出并显示到控制台
     */
    @Test
    public void output() {
        String filePath = "C:\\Users\\Administrator\\Desktop\\Javacode\\java-learning-code\\chapter19\\src\\outputstream_\\a.txt";
        FileOutputStream fileOutputStream = null;
        FileInputStream fileInputStream = null;
        try {
            String outputString = "hi Perfect World!";
            //写入数据时进行覆盖
            //fileOutputStream = new FileOutputStream(filePath);

            //写入数据时进行追加
            fileOutputStream = new FileOutputStream(filePath, true);
            /*for (int i = 0; i < outputString.length(); i++) {
                //write() 写入单个字节数据到文件 若文件不存在将会进行新建并写入(文件目录需要存在)
                fileOutputStream.write(outputString.charAt(i));
            }*/

            //write(byte b[]) 写入 b[] 整个数组的字节数据到文件
            //getBytes() 将字符串转换为 byte[]
            fileOutputStream.write(outputString.getBytes());

            //write(byte b[], int off, int len) 写入 b[] 中部分字节数据到文件
            int off = outputString.indexOf(' ') + 1;//开始下标
            int len = outputString.lastIndexOf(' ') - off;//截取长度
            fileOutputStream.write(outputString.getBytes(), off, len);

            fileInputStream = new FileInputStream(filePath);
            //byte[] inputs = new byte[outputString.length()];
            //byte[] inputs = new byte[len];
            byte[] inputs = new byte[outputString.length() + len];
            fileInputStream.read(inputs);
            System.out.println(new String(inputs));
            //hi Perfect World!Perfect

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
